import React, { useState, useEffect } from 'react';
import { connect } from 'umi';
import _ from 'lodash';
import { fetchMailUpdateBind, fetchMailBind } from '@/services/mail';
import { Modal, Form, message, Input, Select } from 'antd';

const { Option } = Select;

// 弹窗添加邮箱绑定
const MailBindForm = ({
    form,
    data,
    mailBindTemplates,
    visible = false,
    userCode,
    dispatch,
    loginName,
    onOk,
    onCancel
}) => {
    const [loading, setLoading] = useState(false);
    const [isEdit, setIsEdit] = useState(false);

    const compnayEmail = loginName.substring(loginName.indexOf('@') + 1, loginName.length);

    useEffect(() => {
        if (_.size(data) > 0) {
            form.setFieldsValue({ ...data });
            setIsEdit(true);
        } else {
            form.resetFields(); // 清空表单
            setIsEdit(false);
        }
    }, [data]);

    // 表单提交
    const handleSubmit = () => {
        form.validateFields(async (err, values) => {
            if (err) {
                return;
            }
            const { email, emailPwd, mailSuffix } = values;
            const payload = {
                userCode,
                email: email + mailSuffix,
                emailPwd
            };
            let result = null;
            setLoading(true);
            if (isEdit) {
                // 编辑邮箱
                result = await fetchMailUpdateBind(payload);
            } else {
                // 添加邮箱
                result = await fetchMailBind(payload);
            }
            if (result && result.code === 10000) {
                message.success(isEdit ? '编辑成功' : '邮箱添加成功，系统正在拉取，预计5分钟后完成');
                if (onOk) {
                    onOk({ email: email + mailSuffix });
                }
            } else {
                message.error(result.msg);
            }
            dispatch({
                type: 'user/fetchMailBindInfo',
                payload: { userCode }
            });
            setLoading(false);
        });
    };
    return (
        <Modal
            centered
            title={`${isEdit ? '编辑' : '添加'}邮箱`}
            visible={visible}
            okButtonProps={{ loading }}
            onOk={() => {
                handleSubmit();
            }}
            onCancel={() => {
                if (onCancel) {
                    onCancel();
                }
            }}
        >
            <Form hideRequiredMark labelAlign="right" labelCol={{ span: 4 }} wrapperCol={{ span: 18 }}>
                <Form.Item label="邮箱">
                    {form.getFieldDecorator('email', {
                        rules: [{ required: true, message: '邮箱账户不能为空' }]
                    })(
                        <Input
                            disabled={isEdit}
                            autoComplete="off"
                            placeholder="请输入邮箱账号"
                            addonAfter={form.getFieldDecorator('mailSuffix', {
                                initialValue: `@${compnayEmail}`
                            })(
                                <Select style={{ width: 200 }} disabled={isEdit}>
                                    {mailBindTemplates.map(item => (
                                        <Option
                                            value={`@${item.suffix}`}
                                            key={item.suffix}
                                            title={`@${item.suffix}`}
                                        >{`@${item.suffix}`}</Option>
                                    ))}
                                </Select>
                            )}
                        />
                    )}
                </Form.Item>
                <Form.Item label="密码">
                    {form.getFieldDecorator('emailPwd', {
                        rules: [{ required: true, message: '密码不能为空' }]
                    })(<Input autoComplete="new-password" placeholder="请输入邮箱密码" type="password" />)}
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default connect(({ user }) => ({
    loginName: user.currentUser.loginName,
    userCode: user.currentUser.userCode,
    mailBindTemplates: user.mailBindTemplates
}))(Form.create({ name: 'MailBindForm' })(MailBindForm));
